package com.bestcem.xm.award.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.bestcem.xm.common.core.config.mq.XmMessageProducer;
import com.bestcem.xm.common.core.constant.StreamMqBinderConstants;
import com.bestcem.xm.component.security.annotation.AuthIgnore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

@Slf4j
@RestController
@RequestMapping("/scs")
public class ScsTestController {

    @Resource
    private XmMessageProducer messageProducer;

    @AuthIgnore
    @GetMapping("/mq")
    public String mqMessage(@RequestParam(defaultValue = "jack") String name) {
        Map<String, Object> data = new HashMap<>();
        data.put("name", "道友" + name);
        try {
            messageProducer.send(StreamMqBinderConstants.TEST_OUTPUT, data);
        } catch (Exception e) {
            log.error("测试普通消息发送失败:{}", JSONUtil.toJsonStr(data), e);
        }
        return "普通消息";
    }

    @AuthIgnore
    @GetMapping("/delaymq")
    public String delaymqMessage(@RequestParam(defaultValue = "jack") String name) {
        Map<String, Object> data = new HashMap<>();
        data.put("name", "延迟道友" + name);
        try {
            Date delayDate = DateUtil.offset(new Date(), DateField.MINUTE, 5).toJdkDate();

            messageProducer.sendDelay(StreamMqBinderConstants.TEST_OUTPUT, data, delayDate);
        } catch (Exception e) {
            log.error("测试延迟消息发送失败:{}", JSONUtil.toJsonStr(data), e);
        }
        return "延迟5分钟执行";
    }

    @Bean
    public Consumer<GenericMessage<Map<String, Object>>> testDemo() {
        //这里可以接收对象，XmCustomMessageConverter基于jackson转化，熟悉对不上可以使用JsonProperty
        return msg -> log.error("mq消费到:" + msg.getPayload());
    }
}
